/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.misc.dts.conv;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.nothing.common.util.IOUtils;
import org.vacoor.nothing.common.util.Throwables;

import java.io.File;
import java.util.Arrays;

/**
 * @author vacoor
 */
public class PdfToSwfTask {
    private static final Logger LOG = LoggerFactory.getLogger(PdfToSwfTask.class);

    private final File source;
    private final File destination;

    public PdfToSwfTask(File source, File destination) {
        this.source = source;
        this.destination = destination;
    }

    public void execute(int page) {
        try {
            String swftoolsHome = System.getProperty("swftools.home", "");
            swftoolsHome = swftoolsHome.length() < 1 || swftoolsHome.endsWith("/") ? swftoolsHome : swftoolsHome + File.separator;

            /*-
             * 可以使用 -o xx%.swf 来快捷的为每页生成一个 swf
             * -f 选项不启用 搜索时无法高亮 ?!
             * -p 支持 区间
             */
            String[] command = ("pdf2swf -T 9 -t -q -f -s linknameurl -s storeallcharacters" +
                    (page > 0 ? " -p " + page : "") +
                    " -o " + destination.getAbsolutePath() + " " + source.getAbsolutePath()
            ).split(" ");
            command[0] = swftoolsHome + command[0];

            LOG.info("executing: {}", Arrays.toString(command));

            ProcessBuilder builder = new ProcessBuilder(command);
            // 这里直接对class加锁,保证pdf2swf 永远不被同时执行
            synchronized (PdfToSwfTask.class) {
                Process proc = builder.start();
                IOUtils.flow(proc.getInputStream(), System.out, false, false);
                IOUtils.flow(proc.getErrorStream(), System.err, false, false);
                LOG.info("execution result: {}", proc.waitFor());
            }
        } catch (Exception e) {
            LOG.error("Execution failure: {}", e);
            throw Throwables.unchecked(e);
        }
    }
}
